import { onMounted, onUnmounted, Ref } from 'vue'

const useClickOutside = (elementRef: Ref<HTMLElement | null>, callback: (flag: boolean) => void): void => {
  const handler = (e: MouseEvent) => {
    if (elementRef.value) {
      let flag: boolean
      if (elementRef.value.contains(e.target as HTMLElement)) {
        flag = true
      } else {
        flag = false
      }
      callback(flag)
    }
  }
  onMounted(() => {
    document.addEventListener('click', handler)
  })

  onUnmounted(() => {
    document.removeEventListener('click', handler)
  })
}

export default useClickOutside
